﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Kooboo.Commerce.Contexts.Products;
using Kooboo.Commerce.Contexts.Categories;

namespace Kooboo.Commerce.Services
{
    public class SearchService : ServiceBase
    {
        public IEnumerable<SaleProduct> Search(Int32? category, String query, String sort)
        {
            IQueryable<IProduct> products = this.Actor.QueryProducts();

            if (category.HasValue)
            {
                var categories = this.Actor.QueryCategories();
                var find = categories.Where(i => i.Id == category.Value).FirstOrDefault();

                if (find != null)
                {
                    products = find.Products;
                }
            }

            if (string.IsNullOrWhiteSpace(query) == false)
            {
                products = products.Where(i => i.Name.Contains(query));
            }

            if (!string.IsNullOrWhiteSpace(sort))
            {
                switch (sort.ToLower())
                {
                    case "nameaz":
                        products = products.OrderBy(i => i.Name);
                        break;
                    case "nameza":
                        products = products.OrderByDescending(i => i.Name);
                        break;
                    case "pricelh":
                        //  products = products.OrderBy(i => i.RetailPrice);
                        break;
                    case "pricehl":
                        //  products = products.OrderByDescending(i => i.RetailPrice);
                        break;
                    default:
                        break;
                }
            }

            return products.SelectMany(i => i.SaleItems).Select(
                i => new SaleProduct()
                {
                    ProductId = i.Product.Id,
                    Price = i.RetailPrice,
                    Name = i.Product.Name,
                    Thumbnail = i.Product.ProductImages.OrderByDescending(m => m.CoverImage).Select(m => m.Name).FirstOrDefault()
                }).AsEnumerable();
        }
    }
}
